import 'package:safetymonitor/app/components/time/MultiWheelTimePickerTimePeriod.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/gen/assets.gen.dart';
import 'package:safetymonitor/modules/home/home_page/home_page_control.dart';
import 'package:syncfusion_flutter_charts/charts.dart' as charts;
import 'controller.dart';

///环境监测
class EnvironmentalMonitoringPage extends StatelessWidget {
  EnvironmentalMonitoringPage({super.key});

  final controller = Get.put(EnvironmentalMonitoringController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
        init: controller,
        builder: (_) {
          return _showDataUi();
        });
  }

  /// 顶部筛选公司系统
  Widget _buildFiltersOne() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        _selectType('选企业'),
        _selectType('选系统'),
      ],
    );
  }

  /// 顶部筛选类型设备
  Widget _buildFiltersTwo() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        _selectType('选类型'),
        _selectType('选设备'),
      ],
    );
  }

  /// 历史数据图表
//   Widget _buildHistoryChart() {
//     return LineChart(
//       duration: const Duration(milliseconds: 150), // Optional
//       curve: Curves.linear, // Optional,
//       LineChartData(
//         //LineTouchData保存触摸交互详细信息
//         lineTouchData: LineTouchData(
//           //LineTouchTooltipData ，确定如何在触摸点上显示工具提示（显示工具提示气泡的外观）
//           touchTooltipData: LineTouchTooltipData(
//             maxContentWidth: 180,
//             //工具提示的填充
//             tooltipPadding: const EdgeInsets.all(10),
//             //工具提示气泡的背景角半径
//             tooltipRoundedRadius: 8,
//             //通过给定的LineBarSpot列表检索LineTooltipItem列表的回调
//             getTooltipItems: (List<LineBarSpot> touchedSpots) {
//               return touchedSpots.map((e) {
//                 return LineTooltipItem(
//                   '''${controller.historyDataTimes[e.x.toInt()]}
// ${controller.name}      ${e.y}''',
//                   const TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: Colors.white),
//                 );
//               }).toList();
//             },
//           ),
//           //如果您想要内置的触摸处理（在触摸点上显示工具提示气泡和指示器），请设置为true
//           handleBuiltInTouches: true,
//         ),
//
//         //网格数据
//         gridData: FlGridData(
//           show: true,
//           drawVerticalLine: false,
//           getDrawingHorizontalLine: (value) {
//             return const FlLine(
//               color: Color.fromARGB(43, 88, 91, 94),
//               strokeWidth: 1,
//               dashArray: [4, 4], // 设置虚线样式，数组中的数字分别代表实线部分长度和空隙部分长度
//             );
//           },
//         ),
//         //上下左右数据
//         titlesData: FlTitlesData(
//           show: true,
//           rightTitles: const AxisTitles(
//             sideTitles: SideTitles(showTitles: false),
//           ),
//           topTitles: const AxisTitles(
//             sideTitles: SideTitles(showTitles: false),
//           ),
//           bottomTitles: AxisTitles(
//             sideTitles: SideTitles(
//                 showTitles: true,
//                 getTitlesWidget: (val, meta) {
//                   return Text(
//                     '${controller.historyDataTimes[val.toInt()].split(' ')[0]}\n${controller.historyDataTimes[val.toInt()].split(' ')[1]}',
//                     style: const TextStyle(
//                       fontSize: 5,
//                       color: Color(0xff6C779C),
//                     ),
//                   );
//                 }),
//           ),
//           leftTitles: AxisTitles(
//             sideTitles: SideTitles(
//                 showTitles: true,
//                 reservedSize: 32.w,
//                 getTitlesWidget: (val, meta) {
//                   return Text(
//                     controller.isNotEmpty ? val.toStringAsFixed(2) : val.toStringAsFixed(1),
//                     style: const TextStyle(
//                       fontSize: 10,
//                       color: Color(0xff6C779C),
//                     ),
//                   );
//                 }),
//           ),
//         ),
//         //边界数据
//         borderData: FlBorderData(show: false),
//         //线条数据 LineChartBarData列表显示图表的线条，它们堆叠在一起，可以相互叠加绘制
//         lineBarsData: [
//           LineChartBarData(
//             spots: controller.historyData,
//             isCurved: false,
//             barWidth: 2,
//             isStrokeCapRound: true,
//             color: Colors.blue,
//             dotData: const FlDotData(show: true),
//             belowBarData: BarAreaData(show: false),
//           ),
//         ],
//       ),
//     );
//   }

  Widget _buildNewHistoryChart() {
    return SizedBox(
      height: 310.w,
      child: charts.SfCartesianChart(
          // 启用缩放
          zoomPanBehavior: charts.ZoomPanBehavior(
            enablePanning: true,
            // 允许平移
            // enableMouseWheelZooming: true,//启用或禁用鼠标滚轮缩放。
            // enableSelectionZooming: true, //启用或禁用选择缩放。
            enableDoubleTapZooming: true,
            //启用或禁用双击缩放。
            enablePinching: true,
            zoomMode: charts.ZoomMode.x,
            // 设置缩放模式
            selectionRectBorderWidth: 1, //选择缩放矩形的边框宽度
            // panMode: PanMode.xy, // 设置平移模式
          ),
          legend: const charts.Legend(
            isVisible: true,
            position: charts.LegendPosition.top,
            overflowMode: charts.LegendItemOverflowMode.wrap,
          ),
          // 设置x轴文字宽度
          primaryXAxis: const charts.CategoryAxis(
            // 设置x轴文字宽度
            majorGridLines: charts.MajorGridLines(
              width: 0,
            ),
            // 设置边框为虚线
            axisLine: charts.AxisLine(
              dashArray: <double>[3, 3],
            ),
            majorTickLines: charts.MajorTickLines(
              width: 0,
            ),
          ),
          primaryYAxis: const charts.NumericAxis(
            majorGridLines: charts.MajorGridLines(
              dashArray: <double>[3, 3],
            ),
            axisLine: charts.AxisLine(
              dashArray: <double>[3, 3],
            ),
            majorTickLines: charts.MajorTickLines(
              width: 0,
            ),
          ),
          plotAreaBorderWidth: 0,
          //跟踪球
          trackballBehavior: charts.TrackballBehavior(
            //纵向选择指示器
            activationMode: charts.ActivationMode.singleTap,
            enable: true,
            tooltipAlignment: charts.ChartAlignment.center,
            // 线的颜色
            lineColor: const Color(0xff6DDF9A),
            //工具提示位置(顶部)
            //跟踪球始终显示(纵向选择指示器)
            tooltipDisplayMode: charts.TrackballDisplayMode.groupAllPoints,
          ),
          series: controller.lineData),
    );
  }

  Widget _selectType(String name) {
    return Container(
      width: 144.w,
      height: 32.w,
      // margin:  EdgeInsets.only(right: 16.w,left: 16.w),
      decoration: BoxDecoration(color: Colors.white, border: Border.all(color: const Color(0xffDCE1EA)), borderRadius: BorderRadius.circular(6)),
      child: Row(
        children: [
          AppGaps.hGap12,
          Expanded(
              child: Text(
            controller.getString(name: name),
            style: TextStyles.grey_14,
            maxLines: 1,
          )),
          Visibility(
            visible: !(name == '选企业' && controller.userEnvCompanyTreeEntity?.length == 1),
            child: const Icon(
              Icons.keyboard_arrow_down,
              color: AppColors.font_color_gray,
            ),
          ),
          const SizedBox(
            width: 8,
          ),
        ],
      ),
    ).clickOnce(() {
      controller.selectCompanyOn(name);
    });
  }

  Widget _showDataUi() {
    if (Get.find<HomePageControl>().envCompanyTreeEntity2.isNotEmpty) {
      controller.userEnvCompanyTreeEntity = Get.find<HomePageControl>().envCompanyTreeEntity2;
      // Get.find<HomePageControl>().envCompanyTreeEntity.where((e) => e.companyType == 2 || e.companyType == 0).toSet().toList();

      //如果就只有一家企业 就显示直接显示
      if (controller.userEnvCompanyTreeEntity?.length == 1) {
        controller.selectGs = controller.userEnvCompanyTreeEntity?[0];
        controller.childrenXt = controller.userEnvCompanyTreeEntity?[0].children;
      }
      return Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(15.w)),
        ),
        child: SingleChildScrollView(
          child: Column(
            children: [
              AppGaps.vGap10,
              _buildFiltersOne(),
              AppGaps.vGap6,
              _buildFiltersTwo(),
              _selectTime(),
              // const Divider(color: Color(0xffE2E8FD)),
              AppGaps.vGap16,
              Row(
                children: [
                  AppGaps.hGap20,
                  SvgPicture.asset(Assets.svg.iconBlueStar),
                  AppGaps.hGap8,
                  Text(
                    '环境监测',
                    style: TextStyle(color: const Color(0xFF1D3452), fontSize: 15.sp, fontWeight: FontWeight.w500),
                  )
                ],
              ),
              AppGaps.vGap16,
              controller.lineData.isNotEmpty
                  ?
                  // SizedBox(
                  //         height: 220.w,
                  //         width: 320.w,
                  //         child: _buildHistoryChart(),
                  //       )
                  _buildNewHistoryChart()
                  : Center(
                      child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        SvgPicture.asset('assets/svg/zhiban_empty_bg.svg'),
                        Text(
                          '暂无内容',
                          style: TextStyle(
                            color: const Color(0xFFC7CEE5),
                            fontSize: 14.sp,
                          ),
                        ),
                      ],
                    )),
            ],
          ),
        ),
      );
    } else {
      // 显示加载指示器
      return const Center(child: CircularProgressIndicator());
    }
  }

  Widget _selectTime() {
    return Container(
      margin: EdgeInsets.only(left: 26.w, right: 26.w, top: 10.w),
      padding: EdgeInsets.only(left: 12.w, right: 12.w, top: 6.w, bottom: 6.w),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8.w),
          border: Border.all(
            color: AppColors.font_color_gray.withOpacity(0.3),
            width: 1,
          )),
      child: Row(
        children: [
          SvgPicture.asset('assets/svg/icon_calendar.svg'),
          Expanded(
              child: Text(
            controller.startDate,
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w400,
              color: controller.startDate == '开始时间' ? const Color(0xffA0A7B5) : const Color(0xff666666),
            ),
          )),
          AppGaps.hGap5,
          Text(
            '至',
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w400,
              color: AppColors.font_color_black,
            ),
          ),
          AppGaps.hGap5,
          Expanded(
              child: Text(
            controller.endDate,
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w400,
              color: controller.endDate == '结束时间' ? const Color(0xffA0A7B5) : const Color(0xff666666),
            ),
          )),
        ],
      ).click(() {
        // if (controller.queryParams == null) {
        //   AppToast.show('请先选择企业,系统，类型，设备~');
        //   return;
        // }
        MultiWheelTimePickerTimePeriod.show(
          initialDate: controller.endDate,
          pattern: 'yyyy-MM-dd',
          onConfirm: (selectedDate) {
            controller.startDate = '$selectedDate 00:00:00';
            controller.endDate = '$selectedDate 23:59:59';
            controller.getNewLineChart();
          },
          disabledDate: DateTime.now(), // 禁用的日期限制
        );

        // MultiWheelTimePickerTimePeriod.show(
        //   initialStartDate: controller.startDate,
        //   initialEndDate: controller.endDate,
        //   maxYear:DateTime.now().year,
        //   minYear: DateTime.now().year,
        //   //目前显示当月
        //   showMonthsList:[DateTime.now().month],
        //   isShowCurrentDay: true,
        //   onStartEndConfirm: (start, end) {
        //     controller.startDate = start;
        //     controller.endDate = end;
        //     controller.getNewLineChart();
        //   },
        //   isRange: true, // 启用时间段选择
        //   disabledDate: DateTime.now(), // 禁用的日期限制
        // );
      }),
    );
  }
}
